package com.qfedu.controller;

import com.qfedu.entity.Address;
import com.qfedu.entity.User;
import com.qfedu.service.AddressService;
import com.qfedu.service.impl.AddressServiceImpl;
import com.qfedu.utils.BaseServlet;
import com.qfedu.utils.Constants;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;


@WebServlet("/address")
public class AddressServlet extends BaseServlet {
    private AddressService addressService = null;

    @Override
    public void init() throws ServletException {
        addressService = new AddressServiceImpl();
    }

    /**
     * 添加收货地址
     * @param request
     * @param response
     * @return
     */
    public String add(HttpServletRequest request, HttpServletResponse response){
        String aname = request.getParameter("aname");
        String aphone = request.getParameter("aphone");
        String adetail = request.getParameter("adetail");
        int uid = Integer.valueOf(request.getParameter("uid"));
        Address address = new Address(aname, aphone, adetail,uid);
        int num = addressService.addAddress(address);
        return Constants.FORWARD + "/address.do?method=show";
    }

    /**
     * 修改数据
     * @param request
     * @param response
     * @return
     */
    public String update(HttpServletRequest request, HttpServletResponse response){
        int aid = Integer.valueOf(request.getParameter("aid"));
        String aname = request.getParameter("aname");
        String aphone = request.getParameter("aphone");
        String adetail = request.getParameter("adetail");
        Address address = new Address(aid, aname, aphone, adetail);
        int num = addressService.updateAddress(address);
        return Constants.FORWARD + "/address.do?method=show";

    }

    /**
     * 删除一条地址数据
     * @param request
     * @param response
     * @return
     */
    public String delete(HttpServletRequest request, HttpServletResponse response){
        String aidStr = request.getParameter("aid");
        int aid = 0;
        if (aidStr != null){
            aid = Integer.valueOf(aidStr);
        }
        int num = addressService.deleteAddress(aid);
        return Constants.FORWARD + "/address.do?method=show";

    }

    /**
     *  设置地址为默认
     * @param request
     * @param response
     * @return
     */
    public String setDefault(HttpServletRequest request, HttpServletResponse response) {
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        int uid = loginUser.getUid();
        int aid = Integer.valueOf(request.getParameter("aid"));
        addressService.emptyDefault(uid);
        addressService.defaultAddr(aid);
        return Constants.FORWARD + "/address.do?method=show";
    }

}
